﻿//C#MVC-HDS201810-23
var KeyCode = {};//id加密码串
var KeyFocusId = "";//当前行id

//查询
function locate()
{
    //form1.reset();
    ShowModal("popLocate", LocateText, "提示信息");
}

function GetKeyCode(id) {    
    return KeyCode[id];
}

//弹出框
function ShowModal(id, title, info) {
    var layer = layui.layer; //独立版的layer无需执行这一句    
    layer.open({
        type: 1,//0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
        title:title,
        content: $('#' + id),
        area: [$('#'+id).width()+'px']
    });
}

//关闭
function HideModal(id) {
    layui.layer.closeAll();
}

//url弹出框
function ShowModalUrl(id, url, title, info, width, height) {
    //layui.use('layer', function () { //独立版的layer无需执行这一句
        var layer = layui.layer; //独立版的layer无需执行这一句
        var index = layer.open({
            type: 2,//0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
            id: id,
            content: url,
            title: title,
            area: [width + 'px', height + 'px'],
            maxmin: true
        });
        //layer.full(index);
    //});
}

//增加
function add() {
    var url = "";
    if (arguments.length > 0 && arguments[0] != "")
        url = arguments[0] + "?" + UrlAddPara + "&id=-1" + "&tmp=" + new Date().getTime();
    else
        url = FileUrl + "?" + UrlAddPara + "&id=-1" + "&tmp=" + new Date().getTime();
    //if(KeyFieldName!="id") url+="&"+KeyFieldName+"="+id;

    if (NewWindow) {//????
        if (typeof (parent.AddWin) != "undefined")
            parent.AddWin(url, AddText);
        else if (typeof (parent.parent.AddWin) != "undefined")
            parent.parent.AddWin(url, AddText);
        else
            location.href = url;
    }
    else {
        ShowModalUrl("popEdit", url, AddText, PromptInfo, PopEditWidth, PopEditHeight);
    }
}

//修改
function edit() {
    if (!IsEdit) return;
    var id = KeyFocusId;
    var title = EditText;// + $("#dgrid .GridViewFocus").attr("title");
    if (id) {
        var code = KeyCode[KeyFocusId];
        var url = FileUrl + "?" + UrlEditPara + "&id=" + id + "&keyCode=" + code + "&tmp=" + new Date().getTime();
        if (KeyFieldName != "id") url += "&" + KeyFieldName + "=" + id;

        if (NewWindow) {//????
            if (typeof (parent.AddWin) != "undefined")
                parent.AddWin(url, title);
            else if (typeof (parent.parent.AddWin) != "undefined")
                parent.parent.AddWin(url, title);
            else
                location.href = url;
        }
        else {
            ShowModalUrl("popEdit", url, title, PromptInfo, PopEditWidth, PopEditHeight);
        }

    } else
        layui.layer.msg('您没有选择一条记录！');
}

//删除
function del(prompt)//删除
{
    var KeyValues = "";
    var checkStatus = layui.table.checkStatus('dgrid');
    if (checkStatus.data.length > 0) {
        for (var i = 0; i < checkStatus.data.length; i++) {
            KeyValues += ",'" + checkStatus.data[i][KeyFieldName] + "'";
        }
    } else {
        layui.layer.msg("你没有选择记录！");
        return;
    }

    layer.confirm(prompt, function (index) {
        KeyValues = KeyValues.substring(1);
        layer.close(index);
        $.ajax({
            type: 'POST',
            url: DelUrl,//"Del.data",
            data: {
                //type:DelType,
                KeyValues: KeyValues,
                t: new Date().getTime()
            },
            dataType: "json",
            success: function (data) {
                layui.layer.msg(data.message);
                if (data.code == "0000") {
                    GoPage(CurPage);
                }
            }
        });
    });
}

//数据页
function GoPage(page) {
    CurPage = page;
    $.ajax({
        type: 'POST',
        url: DataPageUrl,//DataPage.html
        data: {            
            CurPage: CurPage,
            PageSize: PageSize,
            OrderField: OrderField,
            OrderType: OrderType,
            LocatePara: LocatePara,
            CustomPara: CustomPara,
            t: new Date().getTime()
        },
        dataType: "json",
        success: function (data) {
            ShowData(CurPage,data.data);
        }
    });
}

//显示数据
function ShowData(CurPage, data) {
    //列
    KeyCode = data.KeyCode;
    var isTotal = false;
    for (var key in data.SumPara) {
        isTotal = true;
        break;
    }
    var cols = [[]];      
    var i = 0;
    if (data.isCheck) cols[0][i++] = { type: 'checkbox' };
    for (var key in data.Column) {
        var text = "";
        if (isTotal) {
            var sumValue = data.SumPara[key];
            if (i == 0 || (data.isCheck && i == 1)) {
                text = "合计";
            }
            if (sumValue != undefined) {
                text = (text != "" ? ":" : "") + sumValue;
            }
        }
        var cl = data.Column[key];
        var align = cl.TextAlign == 1 ? "right" : (cl.TextAlign == 2 ? "center" : "left");
        cols[0][i++] = { field: key, title: cl.HeadText, style: cl.Style, sort: cl.IsSort, totalRowText: text, align: align, width: (cl.Width > 0 ? cl.Width:"") };
    }  
    
      
    //数据显示
    //layui.use('table', function () {
        var table = layui.table;
        table.render({
            id: 'dgrid',
            elem: '#dgrid',
            height: TableHeight,
            data: data.Data,   
            limit: data.PageSize,
            page: false,
            totalRow: isTotal,
            cols: cols
        });

        //监听排序
        table.on('sort(dgrid)', function (obj) {           
            OrderField = obj.field;
            OrderType = obj.type == "asc" ? 0 : 1; //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）
            GoPage(CurPage);
        });
        //监听单击
        table.on('row(dgrid)', function (obj) {
            var data = obj.data;
            KeyFocusId=data[KeyFieldName];
        });
        table.on('rowDouble(dgrid)', function (obj) {
            var data = obj.data;
            KeyFocusId = data[KeyFieldName];
            edit();
        });
    //});
    //页码条
    //layui.use('laypage', function () {
        var laypage = layui.laypage;
        //if (!isTotal)
        //    $("#DataPageHTML").css("border-top", "solid 1px #e6e6e6");
        //执行一个laypage实例
        laypage.render({
            elem: 'DataPageHTML',
            curr: CurPage,
            limit: data.PageSize,
            limits: [10, 20, 50, 100],
            groups: 5,
            //first: '<<',
            prev: '<i class="layui-icon"></i>',
            next: '<i class="layui-icon"></i>',
            //last: '>>',
            count: data.RowCount, //数据总数，从服务端得到
            layout: ['prev', 'page', 'next', 'skip', 'count', 'limit'],
            theme: 'page',
            jump: function (obj, first) {
                //首次不执行
                if (!first) {
                    PageSize = obj.limit;
                    GoPage(obj.curr);
                }
            }
        });
    //});
}

//ajax调用
function Do(url, data) {
    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        dataType: "json",
        success: function (data) {            
            if (data.code == "0000") {
                layui.layer.msg(data.message, {
                     time: 500 //2秒关闭（如果不配置，默认是3秒）
                }, function () {
                    GoPage(CurPage);
                });
            }
            else
                layui.layer.msg(data.message);
        }
    });
}
function Print()
{
    alert("发票格式先设置");
}
//导入
function importXls() {
    ShowModalUrl('popEdit', ImportUrl, ImportText, PromptInfo, 530, 300);
}

//导出
function exportXls() {
    var form = $("#frmExport");
    if (form) form.remove();

    form = $("<form>");//定义一个form表单
    form.attr("id", "frmExport");
    form.attr("style", "display:none");
    form.attr("target", "");
    form.attr("method", "post");
    form.attr("action", ExportUrl);
    $("body").append(form);//将表单放置在web中
    var input = $("<input>"); input.attr("type", "hidden"); input.attr("name", "OrderField"); input.attr("value", OrderField); form.append(input);
    input = $("<input>"); input.attr("type", "hidden"); input.attr("name", "OrderType"); input.attr("value", OrderType); form.append(input);
    input = $("<input>"); input.attr("type", "hidden"); input.attr("name", "LocatePara"); input.attr("value", LocatePara); form.append(input);

    form.submit();//表单提交
}
